package com.nl.controller.web.service;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.nl.controller.web.bean.*;
import com.nl.controller.web.mapper.SmsAreaMapper;
import com.nl.controller.web.mapper.impl.SmsAreaMapperImpl;
import com.nl.controller.xuyi.bean.xuyimap.XuYiGetStationsReq;
import com.nl.controller.xuyi.bean.xuyimap.XuYiGetStationsResp;
import com.nl.controller.xuyi.service.XuYiMapService;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Base64Utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.model.BaseResult;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.MD5;
import com.nl.controller.web.bean.cityCountySyn.CityCountyInfo;
import com.nl.controller.web.bean.sendLimit.SendLimitReq;
import com.nl.controller.web.bean.taskDetailSyn.LimitInfo;
import com.nl.controller.web.bean.taskDetailSyn.StationInfo;
import com.nl.controller.web.mapper.SmsInterfacesMapper;
import com.nl.controller.web.mapper.SmsMgrTemplateInfoMapper;
import com.nl.controller.web.util.DoubleUtil;
import com.nl.controller.web.util.GZipUtil;
import com.nl.controller.web.util.HttpClientUtil;
import com.nl.controller.web.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsInterfacesService {
	@Autowired
    private SmsInterfacesMapper smsInterfacesMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private SmsMgrTemplateInfoService smsMgrTemplateInfoService;
	@Autowired
    private SmsAreaService smsAreaService;
	@Autowired
    private SmsMgrTemplateInfoMapper smsMgrTemplateInfoMapper;
	@Autowired
	private SmsUserService smsUserService;
	@Autowired
	private ChangeSynchronizationInterfaceService changeSynchronizationInterfaceService;
	@Autowired
	private LoginService loginService;
	@Autowired
	private SmsAreaMapperImpl smsAreaMapperImpl;

	@Autowired
	private SmsAreaMapper smsAreaMapper;

	@Autowired
	private XuYiMapService xuYiMapService;

	//private final String interfacesUrl="http://10.32.45.139:8080";//老接口地址
	//private final String interfacesUrl="http://10.209.169.125:8080"; //新接口地址
	private final String interfacesUrl="http://10.32.248.23:18993";
	public String httpPostWithJSON(String url, JSONObject jsonParam)
            throws Exception {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        org.apache.http.HttpEntity entity = null;
        String result = "";
        try {
            httpclient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            StringEntity entityParam = new StringEntity(jsonParam.toString(),
                    "utf-8");// 解决中文乱码问题
            entityParam.setContentEncoding("UTF-8");
            entityParam.setContentType("application/json");
            httpPost.setEntity(entityParam);
            // 设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
                    100000);
            // 设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 100000);
            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }
//	@SystemServiceLog(description = "人流量信息查询接口", value = false)
	public Map<String, Object> qryPersonFlows(com.alibaba.fastjson.JSONObject json){
		Map<String,Object> map=new HashMap<String, Object>();
        String retCode="-1";
        String retMsg="";
        JSONObject req = new JSONObject();
        String resp="";
        try {
          	 req=this.initPersonFlowsReq(json);
          	 long startTime=System.currentTimeMillis();
      	     resp=this.httpPostWithJSON(interfacesUrl, req);

      	     long endTime=System.currentTimeMillis();
             float excTime=(float)(endTime-startTime)/1000;
             log.info("【人流量查询接口】请求执行时间：{}",excTime+"s");
      	     resp = GZipUtil.gunzip(resp);
      	     //log.info("人流量信息查询接口回参(解压后)：{}",resp);
      	     long startTime2=System.currentTimeMillis();
          	 map=this.readPersonFlowsResp(resp);
          	 long endTime2=System.currentTimeMillis();
             float excTime2=(float)(endTime2-startTime2)/1000;
             log.info("【人流量查询接口】解析执行时间：{}",excTime2+"s");
//          	 commonService.createSmsOperLog("6", "调用人流量信息查询接口", "0", "项目维护管理");
		} catch (Exception e){
			retMsg="查询人流量信息接口异常,error:"+e.getMessage();
			map.put("retCode", retCode);
		  	map.put("retMsg", retMsg);
			e.printStackTrace();
//			commonService.createSmsOperLog("6", "调用人流量信息查询接口", "1", "项目维护管理");
		}
  	  	return map;
	}
	/**
	 * desc:初始化人流量信息查询接口请求报文
	 * @author syl
	 * @Date 2019年7月19日 下午1:59:12
	 * @param parm
	 * @return
	 */
	private JSONObject initPersonFlowsReq(JSONObject parm){
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    	  parm.put("streamSeq", sdf.format(new Date())+this.getSeq());
    	  parm.put("flag", "traffic_info");
    	  return parm;
	}
	/**
	 * desc:获取序列号
	 * @author syl
	 * @Date 2019年7月17日 下午6:11:48
	 * @return
	 */
	public String getSeq()  {
		String seq="";
		try {
			seq = smsInterfacesMapper.getInterfacesSeq();
		} catch (Exception e) {
			e.printStackTrace();
            log.error("获取序列号");
		}
		return seq;
	}
	/**
	 * desc:解析人流量返回报文
	 * @author syl
	 * @Date 2019年7月19日 上午10:59:58
	 * @param resp
	 * @return
	 */
	private Map<String, Object> readPersonFlowsResp(String resp){
        String retCode="-1";
        Map<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);
            JSONArray infoData=JSONArray.parseArray(jsonObject.getString("infoData"));
            log.info("【人流量查询接口】热力信息列表长度：{}",infoData.size());
            String streamSeq = jsonObject.getString("streamSeq");
            log.info("【人流量查询接口】人流量返回报文流水号：{}",streamSeq);
            if(infoData!=null&&infoData.size()>0){
                retCode="0";
            }
            retMap.put("retCode", retCode);
            retMap.put("infoData", infoData);
            retMap.put("streamSeq", streamSeq);
        }
        return retMap;
    }

	/**
	 * desc:项目发送范围同步接口
	 * @author syl
	 * @Date 2019年7月19日 上午11:15:06
	 * @param json
	 * @return
	 */
	@SystemServiceLog(description = "项目发送范围同步接口", value = false)
	public Map<String, Object> sendMgrLimit(com.alibaba.fastjson.JSONObject json,String flag ){
		Map<String,Object> map= new HashMap<>();
        String retCode="-1";
        String retMsg;
        JSONObject req;
        String resp;
        String cityId = json.getString("cityId");
        try {
          	 req=this.initSendMgrLimitReq(json,flag);
          	log.info("项目发送范围同步接口入参：{}",req);
         	 //resp = "{\"mgrId\":\"112321321\",\"stationId\":\"1000001,1000002,1000003\",\"resultCode\":\"0\",\"resultDesc\":\"成功\",\"streamSeq\":\"20190704110306100001\"}";
      	     resp=this.httpPostWithJSON(interfacesUrl, req);
      	     resp = GZipUtil.gunzip(resp);
      	     log.info("项目发送范围同步接口回参(解压后)：{}",resp);
          	 map=this.readSendMgrLimitResp(resp);
			 map.put("id",req.getString("mgrId"));
			 map.put("cityId",cityId);
			 String regionId = smsAreaService.getRegionId();
			 map.put("regionId",regionId);
			 if ("0".equals(map.get("retCode"))){
				 addStationTemp(map);
				 map.remove("stationIds");
				}
		} catch (Exception e){
			retMsg="项目发送范围同步接口异常,error:"+e.getMessage();
			map.put("retCode", retCode);
		  	map.put("retMsg", retMsg);
			e.printStackTrace();
		}
  	  	return map;
	}
	public void addStationTemp (Map<String, Object> map){
		String id =  map.get("id").toString();
		String cityId = map.get("cityId").toString();
		String regionId = map.get("regionId").toString();
		List<String> stationIds = Arrays.asList(map.get("stationIds").toString().split(","));
		List<SmsBaseStation> list = new ArrayList<>();
		if (null!=stationIds && stationIds.size()>0){
		for ( String stationId :stationIds ) {
			SmsBaseStation smsBaseStation = new SmsBaseStation();
			smsBaseStation.setId(id);
			smsBaseStation.setCityId(cityId);
			smsBaseStation.setRegionId(regionId);
			smsBaseStation.setStationId(stationId);
			list.add(smsBaseStation);
		}
		}
		smsAreaMapper.delStationTemp(id);
		smsAreaMapperImpl.addSmsBaseStationTemp(list);
	}

	/**
	 * desc:解析项目发送范围接口返回报文
	 * @author syl
	 * @Date 2019年7月19日 下午1:54:36
	 * @param resp
	 * @return
	 */
	private Map<String, Object> readSendMgrLimitResp(String resp){
        String retCode="-1";
        String stationIds = "";
        String resultDesc = "";
        String streamSeq = "";
        String stationCount = "0";
        Map<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);
        	stationIds = jsonObject.getString("stationId");
        	retCode = jsonObject.getString("resultCode");
            resultDesc = jsonObject.getString("resultDesc");
            streamSeq = jsonObject.getString("streamSeq");
            if (!"0".equals(retCode)) {
            	retMap.put("retCode", retCode);
            	retMap.put("stationCount","0");
            	retMap.put("retMsg", "该区域下暂无基站,请重新圈选");
            	return retMap;
		}
        }
        if (!StringUtil.isNull(stationIds)) {
			stationCount = stationIds.split(",").length+"";
			log.info("【项目发送范围接口】基站个数：{}",stationCount);
		}
        //log.info("【项目发送范围接口】基站个数：{}",stationIds.split(",").length);
        log.info("【项目发送范围接口】项目发送范围接口返回报文流水号：{}",streamSeq);
        retMap.put("stationIds", stationIds);
        retMap.put("retCode", retCode);
        retMap.put("retMsg", resultDesc);
        retMap.put("stationCount",stationCount);
        return retMap;
    }
	/**
	 * desc:初始化项目发送范围请求报文
	 * @author syl
	 * @Date 2019年7月19日 下午1:58:54
	 * @param parm
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private JSONObject initSendMgrLimitReq(JSONObject parm,String flag) throws UnsupportedEncodingException{
	  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	  String cityId = parm.getString("cityId");
	  if(cityId.equals("11")){
		  cityId = "512";
	  }else if(cityId.equals("12")){
		  cityId = "517";
	  }else if(cityId.equals("13")){
		  cityId = "527";
	  }else if(cityId.equals("14")){
		  cityId = "250";
	  }else if(cityId.equals("15")){
		  cityId = "518";
	  }else if(cityId.equals("16")){
		  cityId = "516";
	  }else if(cityId.equals("17")){
		  cityId = "519";
	  }else if(cityId.equals("18")){
		  cityId = "511";
	  }else if(cityId.equals("19")){
		  cityId = "510";
	  }else if(cityId.equals("20")){
		  cityId = "513";
	  }else if(cityId.equals("21")){
		  cityId = "523";
	  }else if(cityId.equals("22")){
		  cityId = "515";
	  }else if(cityId.equals("23")){
		  cityId = "514";
	  }
	  parm.put("cityId", cityId);
	  String longAndLatGPS = "";
	  String longAndLats = parm.getString("longAndLats");
	  log.info("----"+longAndLats);
	  if(longAndLats!=null&&!"".equals(longAndLats)){
		 if ("1".equals(flag)) {//气象局入口
			 longAndLats = longAndLats.replace('+', '|');
			 longAndLats = this.toGPS(longAndLats);
			 parm.put("longAndLats", longAndLats);
		} else {
			String[] longAndLatsArray = longAndLats.split("\\+") ;
			  for (int i = 0; i < longAndLatsArray.length; i++) {
				 String[] simpleLongAndLat = longAndLatsArray[i].split(",") ;
				 if (simpleLongAndLat.length==2) {
					 String gps = BdToGPS(simpleLongAndLat[0], simpleLongAndLat[1]);
					if (i ==0 ) {
						longAndLatGPS  = gps;
					}else {
						longAndLatGPS  = longAndLatGPS+"|"+gps;
					}
				 }else{
					 longAndLatGPS=longAndLatGPS+"|"+longAndLatsArray[i];
				 }
			}
			  parm.put("longAndLats", longAndLatGPS);
		}
	  }
  	  parm.put("streamSeq", sdf.format(new Date())+this.getSeq());
  	  parm.put("flag", "program_send");
  	  return parm;
	}
	private static String BdToGPS(String lng,String lat) throws UnsupportedEncodingException{
		String url = "http://api.map.baidu.com/ag/coord/convert";
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("from", "0");
		querys.put("to", "4");
		querys.put("x", lng);
		querys.put("y", lat);
		BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
		if ("0".equals(sendGet.getRetCode())) {
			BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class) ;
			if ("0".equals(data.getError())) {
				String x = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
				String y = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
				Double lngGPS =DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lng)),Double.parseDouble(x));
				Double latGPS =DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lat)),Double.parseDouble(y));
				return lngGPS.toString()+","+latGPS.toString();
			}
		}
		return lng+","+lat;

	}

	public static  String GPSToBd(String lng,String lat) throws UnsupportedEncodingException{
		String url = "http://api.map.baidu.com/ag/coord/convert";
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("from", "0");
		querys.put("to", "4");
		querys.put("x", lng);
		querys.put("y", lat);
		BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
		if ("0".equals(sendGet.getRetCode())) {
			BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class) ;
			if ("0".equals(data.getError())) {
				String x = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
				String y = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
/*				Double lngGPS =DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lng)),Double.parseDouble(x));
				Double latGPS =DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lat)),Double.parseDouble(y));*/
				return x+","+y;
			}
		}
		return lng+","+lat;
	}
	@Transactional
	//@SystemServiceLog(description = "区县字典同步接口", value = false)
	public Map<String, Object> cityCountySyn(String cityCountyList){
		Map<String,Object> map=new HashMap<String, Object>();
        String resultCode="-1";
        String resultDesc="";
        int truncateNum = -1;
        int insertNum = 0;
        int updateNum = 0;
        try {
        	cityCountyList = GZipUtil.gunzip(cityCountyList);
        	JSONObject json = JSON.parseObject(cityCountyList);
        	String LastUpdateTime = (String) json.get("LastUpdateTime");
        	String time = smsInterfacesMapper.getLastUpdateTime();
        	if(LastUpdateTime.equals(time)){
        		resultCode="0";
    			resultDesc = "无需更新";
        	}else{
        		List<CityCountyInfo> list = (List<CityCountyInfo>) json.get("cityCountyList");
            	log.info("【区县字典同步接口】list：{}",list.toString());
            	if(list.size()>0){
            		truncateNum = smsInterfacesMapper.truncateCityCounty();
            		if(truncateNum==0){
            			log.info("清除地市区县表数据成功");
//            			commonService.createSmsOperLog("5", "清除地市区县表数据", "0", "无");
            			insertNum = smsInterfacesMapper.insertCityCounty(list);
            			updateNum = smsInterfacesMapper.updateTime(LastUpdateTime);
                		if(insertNum>0&&updateNum>0){
//                			commonService.createSmsOperLog("2", "插入地市区县表", "0", "无");
                			log.info("清除地市区县表数据成功");
                			resultCode="0";
                			resultDesc = "成功";
//                    		commonService.createSmsOperLog("6", "调用区县字典同步接口", "0", "无");
                			log.info("调用区县字典同步接口成功");
                		}else{
                			resultDesc = "没有数据插入地市区县表";
//                			commonService.createSmsOperLog("2", "插入地市区县表", "1", "无");
                			log.info("插入地市区县表失败");
//                			commonService.createSmsOperLog("6", "调用区县字典同步接口", "1", "无");
                		}
            		}else{
            			resultDesc = "没有清除地市区县表数据";
//            			commonService.createSmsOperLog("5", "清除地市区县表数据", "1", "无");
            			log.info("清除地市区县表数据失败");
            		}
            	}else{
            		resultDesc = "无可插入地市区县表数据";
            	}
        	}
		} catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc="区县字典同步接口异常,error:"+e.getMessage();
			e.printStackTrace();
//			commonService.createSmsOperLog("6", "调用区县字典同步接口", "1", "无");
			log.info("调用区县字典同步接口失败");
		}
        map.put("resultCode", resultCode);
	  	map.put("resultDesc", resultDesc);
  	  	return map;
	}

	/**
	 * desc:任务信息同步接口
	 * @author syl
	 * @Date 2019年9月9日 上午10:33:26
	 * @return
	 */
	@Transactional
	public Map<String, Object> taskDetailSyn(String taskDetailSynReq){
		BaseResult<XuYiGetStationsResp> pxQxjStations = BaseResult.newSuccessInstance();
		List<String> longAndLatList = new ArrayList<>();
		Map<String,Object> map=new HashMap<String, Object>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String resultCode="-1";
        String resultDesc="";
        try {
        	JSONObject json = JSON.parseObject(taskDetailSynReq);
        	if(null!=json && !"".equals(json)){
        		log.info("【任务信息同步接口】json：{}",json.toJSONString());
        		//1.判断是否有重复的taskid
        		String taskId = json.getString("taskId");
        		int isExist = smsInterfacesMapper.isExist(taskId);
        		if (isExist==0) {
        			log.info("任务编码未重复");
        			int localDate = 0;
					//2.获取mgrid
        			String mgrId = smsMgrTemplateInfoMapper.getMgrId();
        			//3.获取发送保存时间（精确到天）
        			Date dateEnd = format.parse((String) json.get("endTime"));
                    Date dateStart = format.parse((String) json.get("startTime"));
                    String endTime = format.format(dateEnd).split(" ")[1];
                    String startTime = format.format(dateStart).split(" ")[1];
                    localDate = (int)((dateEnd.getTime() - dateStart.getTime())/(1000*3600*24));
                    int result = endTime.compareTo(startTime);
                    if (result!=0) {
                    	localDate = localDate+1;
					}
                    System.out.println("====================localDate:"+localDate);

                    String sendObject = json.getString("sendObject");
                    String isLocal = "0";
                    if ("1".equals(sendObject)) {
                    	isLocal = "0";
					}else if("2".equals(sendObject)){
						isLocal = "1";
					}else if("3".equals(sendObject)){
						isLocal = "2";
					}
                    //4.获取阀值
                    String limit = json.getString("limitInfo");
                    LimitInfo limitInfo = JSON.parseObject(limit,LimitInfo.class);
                    int threshold = 0;//总阀值
                    int isThreshold = 0;//0：不设置阀值  1：设置总阀值，但不设置周期阀值  2：设置周期阀值，但不设置总阀值  3：总阀值和周期阀值都设置
                    String cycle = "";//周期阀值类型
                    String cycleThreshold = "0";//周期阀值量
                    if (null != limitInfo && !"".equals(limitInfo)) {
                    	String totalLimit = limitInfo.getTotalLimit();//总阀值
                    	String dayLimit = limitInfo.getDayLimit();//日阀值
						if(!"".equals(totalLimit)&&null!=totalLimit){
							isThreshold = isThreshold+1;
						}
						if(!"".equals(dayLimit)&&null!=dayLimit){
							isThreshold = isThreshold+2;
						}
						if(1==isThreshold){
							threshold = Integer.parseInt(totalLimit);
						}else if (2==isThreshold) {
							cycle = "4";
							cycleThreshold = dayLimit;
						}else if (3==isThreshold) {
							threshold = Integer.parseInt(totalLimit);
							cycle = "4";
							cycleThreshold = dayLimit;
						}
					}
                    //5.根据气象局字典获取对应的地市或区县编码
                    String regionTypeValue = "";//字典对应的地市或区县编码集
                    String sendScopes = json.getString("sendScopes");//接口中获取的编码集
                    String scopeId = json.getString("scopeId");//接口中获取的发送范围编码（地图）
					String longAndLatListString = json.getString("longAndLatList");
					//List<String> longAndLatList = JSONArray.parseArray(longAndLatList1,String.class);

                    String regionType = "";// 发送区域类型 （地图）
                    String cityId = json.getString("cityId");
                    if(sendScopes!=null&& !"".equals(sendScopes)){
                    String[] array = sendScopes.split(",");
                    for(int i=0;i<array.length;i++){
                    	System.out.println(array[i]);
                    	String scopeResult = smsInterfacesMapper.getRegionTypeValue(array[i]);
                    	if (null!=scopeResult && !"".equals(scopeResult)) {
                    		regionTypeValue += scopeResult+",";
                    		log.info("查找"+array[i]+"对应地市或区县编码成功");
						}else {
							log.info("查找"+array[i]+"对应地市或区县编码失败");
						}
                    }
                    if (null!=regionTypeValue && !"".equals(regionTypeValue)) {
                    	regionTypeValue=regionTypeValue.substring(0,regionTypeValue.length()-1);
					}
                    regionType="1";
                    System.out.println("regionTypeValue:"+regionTypeValue);
                    }else if(scopeId!=null&& !"".equals(scopeId)){
                    	SmsMgrTemplateInfo smsMgrTemplateInfo =smsInterfacesMapper.getRegionType(scopeId);
                    	if(null!=smsMgrTemplateInfo && !"".equals(smsMgrTemplateInfo)){
                    	regionTypeValue=smsMgrTemplateInfo.getRegionTypeValue();


                    	regionType=smsMgrTemplateInfo.getRegionType();//1多边形 2长方形 3圆形
                    	if ("1".equals(regionType)) {
                    		regionType = "4";
						}
						if ("2".equals(regionType)) {
							regionType = "3";
						}
						if ("3".equals(regionType)) {
							regionType = "2";
						}
                    	cityId = smsMgrTemplateInfo .getCityId()==null ? "14" : smsMgrTemplateInfo .getCityId();
                    	}else{
                    		 map.put("resultCode", "-1");
                    		 map.put("resultDesc","范围编码为空");
                    		 return map;
                    	}
                    	//沛县气象局直接传范围数据
                    }else if(longAndLatListString!=null&& !"".equals(longAndLatListString)){
                    	longAndLatList = JSONArray.parseArray(longAndLatListString,String.class);

						List<String> lnglatList2 = new ArrayList<>();
						for(String lnglat : longAndLatList){
							lnglat = lnglat.replaceAll("\\|","+");
							JSONObject jsonObject =JSONObject.parseObject(lnglat);
							lnglat = (String) jsonObject.get("longAndLats");
							lnglatList2.add(lnglat);
						}
						for(String lnglat:lnglatList2){
							if(StringUtil.isNull(regionTypeValue)){
								regionTypeValue = lnglat;
							}else{
								regionTypeValue = regionTypeValue+"&"+lnglat;
							}
						}
						//沛县范围类型5，多范围类型
						regionType = "5";

					}
                    //"|"为了请求基站数据，"+"为了展示地图图形
                    regionTypeValue= regionTypeValue.replaceAll("\\|", "+");
                    String extId = smsUserService.findExtIdByCityId(cityId).get(0);
                    //6.将项目添加到项目模板表中
                    int insertResult = smsMgrTemplateInfoService.configureMgrTemplateQXJ(cityId, "", json.getString("taskName"), extId,
                    		json.getString("startTime"), json.getString("endTime"),
                    		isLocal, threshold, String.valueOf(isThreshold), json.getString("mgrContent"), mgrId, "", regionType, regionTypeValue,
                    		"0", "0", "insert", "", cycle, cycleThreshold, String.valueOf(localDate), json.getString("taskId")) ;
                    if (insertResult>0) {
                    	resultCode = "0";
                    	log.info("项目模板表插入成功");
                    	if(longAndLatListString!=null&& !"".equals(longAndLatListString)){

							JSONObject changeSynJson = new JSONObject();
							ChangeData changeData = changeSynchronizationInterfaceService.findChangeByMgrId(mgrId);
							changeData.setStreamSeq(getStreamSeq());
							log.info(" 项目信息：{}", changeData.toString());
							/*json.put("changeData",changeData);*/
							changeSynJson.put("mgrId",changeData.getMgrId());
							changeSynJson.put("checkState",changeData.getCheckState());
							changeSynJson.put("mgrState",changeData.getMgrState());
							changeSynJson.put("sendStart",changeData.getSendStart());
							changeSynJson.put("sendEnd",changeData.getSendEnd());
							changeSynJson.put("streamSeq",changeData.getStreamSeq());
							changeSynJson.put("flag","program_update");
							System.out.println("changeSynJson:"+changeSynJson.toString());
							Map<String, Object> synResult = changeSynchronizationInterfaceService.changeSynchronization(changeSynJson);
							log.info("项目状态变更同步结果；"+synResult.toString());

							//同步基站信息
							List<String> lnglatList2 = new ArrayList<>();
							for(String lnglat : longAndLatList){
								lnglat = lnglat.replaceAll("\\|","+");
								JSONObject jsonObject =JSONObject.parseObject(lnglat);
								lnglat = (String) jsonObject.get("longAndLats");
								lnglatList2.add(lnglat);
							}


							XuYiGetStationsReq xuYiGetStationsReq = new XuYiGetStationsReq();
							xuYiGetStationsReq.setMgrId(mgrId);
							xuYiGetStationsReq.setLongAndLatList(lnglatList2);
							pxQxjStations=xuYiMapService.xuYiGetStations(xuYiGetStationsReq);

                    		String stationCount = pxQxjStations.getData().getStationCount();

							if (stationCount == null || "0".equals(stationCount)) {
								log.info("发送范围同步接口失败，基站数量为0");
								resultDesc = "该范围下无基站："+longAndLatList.toString();
							}else{
								smsAreaService.mapSave(cityId, mgrId, regionType, regionTypeValue, "", "");
								resultDesc = "调用任务信息同步接口成功";
								//成功后触发审核下行
								StringBuffer sbf = new StringBuffer();
								sbf.append("沛县气象局新建项目:"+json.getString("taskName")+",短信内容 :"+json.getString("mgrContent"));
								sbf.append(";审核通过请回复\'Y-"+mgrId+"+1"+"-YJ\'");
								sbf.append(";审核不通过请回复\'N-"+mgrId+"+1"+"-YJ\'");
								List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId(cityId);
								if (null!= smsUsers && !smsUsers.isEmpty()) {
									for (SmsUsers smsUser : smsUsers) {
										loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
										log.info("手机号" + smsUser.getMsisdn());
										log.info(sbf.toString());
									}
								}
							}

						}else{
							//7.调用项目发送范围同步接口获取返回的基站
							SendLimitReq sendLimitReq = new SendLimitReq();
							sendLimitReq.setCheckState("2");//默认未审核
							sendLimitReq.setCityId(cityId);//默认全省项目
							sendLimitReq.setCountyId("");
							sendLimitReq.setMgrId(mgrId);
							sendLimitReq.setMgrState("0");//默认项目开启
							//sendLimitReq.setScopeType("0");//默认行政区域划分类型
							if("1".equals(regionType)){
								sendLimitReq.setScopeType("0");//默认行政区域划分类型
								sendLimitReq.setCountyId(regionTypeValue);
							}else{//地图//1多边形 2长方形 3圆形
								sendLimitReq.setScopeType("1");
								sendLimitReq.setLongAndLats(regionTypeValue);
							}
							sendLimitReq.setSendEnd(json.getString("endTime"));
							sendLimitReq.setSendStart(json.getString("startTime"));
							JSONObject sendLimitJson = (JSONObject) JSON.toJSON(sendLimitReq);
							Map<String, Object> sendLimitMap = this.sendMgrLimit(sendLimitJson,"1");//调用项目发送范围同步接口
							log.info("调用IT项目发送范围同步接口返回报文:"+sendLimitMap);
							String stationCount =  sendLimitMap.get("stationCount").toString();
							if (stationCount == null || "0".equals(stationCount)) {
								log.info("发送范围同步接口失败:"+sendLimitMap);
								resultDesc = "该范围下无基站："+sendLimitMap.toString();
							}else{
								//8.修改项目模板表中数据并且更新表基站
								String regionId = sendLimitMap.get("regionId").toString();
								smsAreaService.mapSave(cityId, mgrId, regionType, regionTypeValue, "", regionId);
								resultDesc = "调用任务信息同步接口成功";
								//成功后触发审核下行
								StringBuffer sbf = new StringBuffer();
								sbf.append("气象局新建项目:"+json.getString("taskName")+",短信内容 :"+json.getString("mgrContent"));
								sbf.append(";审核通过请回复\'Y-"+mgrId+"+1"+"-YJ\'");
								sbf.append(";审核不通过请回复\'N-"+mgrId+"+1"+"-YJ\'");
								List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId(cityId);
								if (null!= smsUsers && !smsUsers.isEmpty()) {
									for (SmsUsers smsUser : smsUsers) {
										loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
										log.info("手机号" + smsUser.getMsisdn());
										log.info(sbf.toString());
									}
								}
							}
						}
					}else {
						log.info("项目模板表插入失败");
					}
				}else {
					log.info("任务编码已存在");
					resultDesc = "已存在需要同步的任务信息";
				}
        	}else {
        		resultDesc = "未获取到需要同步的任务信息";
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc="任务信息同步接口异常,error:"+e.getMessage();
			e.printStackTrace();
			log.info("调用任务信息同步接口失败");
		}
        map.put("resultCode", resultCode);
	  	map.put("resultDesc", resultDesc);
		return map;
	}
	/**desc: 判断token
	 * @author zhangh
	 * @param authentication
	 * @return
	 */
	public Map<String, String> authentication(String authentication) {
		Map< String, String> map = new HashMap<String, String>();
		String key = "yjfbzx";
		map.put("isPass", "0");
		JSONObject json = JSON.parseObject(authentication);
		if(null!=json && !"".equals(json)){
			String token = json.getString("token");
			String cityId = json.getString("cityId");
			String timeStamp = json.getString("timeStamp");
			String scopeId = json.getString("scopeId");
			String flag = json.getString("flag");
			String requestFlag = json.getString("requestFlag") == null ? "0" : json.getString("requestFlag");
			log.info("==="+token+","+cityId+","+timeStamp);
			MD5 md5 = new MD5();
			if (!StringUtil.isNull(flag) && !StringUtil.isNull(token) && !StringUtil.isNull(cityId) && !StringUtil.isNull(timeStamp)) {
				try {
					SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
					Date now = new Date();
					Date requestDate = format.parse(timeStamp);
					//180000
					if (now.getTime() - requestDate.getTime()<180000 && now.getTime() - requestDate.getTime()>0) {
						log.info(now.getTime() - requestDate.getTime()+"");
						String nowToken = md5.getMD5ofStr(cityId+timeStamp+key);
						if (token.equals(nowToken)) {
							log.info("鉴权通过");
							map.put("isPass", "1");
							map.put("cityId", cityId);
							map.put("scopeId", scopeId);
							map.put("flag", flag);
							map.put("requestFlag", requestFlag);
							return map;
						}
					}
				} catch (ParseException e) {
					log.error(e.toString());
					e.printStackTrace();
				}
			}
		}
		return map;
	}

	/**
	  * desc:气象局圈划范围同步接口
	  * @author ll
	  * @Date 2019年11月18日 下午3:40:04
	  * @param json
	  * @return
	  */
	@SystemServiceLog(description = "气象局圈划范围同步接口", value = false)
	public Map<String, Object> synScope(com.alibaba.fastjson.JSONObject json){
		Map<String,Object> map=new HashMap<String, Object>();
       String retCode="-1";
       String retMsg="";
       JSONObject req = new JSONObject();
       String resp="";
       try {
         	 req=this.initSynScopeReq(json);
     	     //废弃，默认返回成功
         	 resp = "{\"resultCode\":\"0\",\"resultDesc\":\"成功\"}";
     	     log.info("项目发送范围同步接口回参：{}",resp);
         	 map=this.readSynScopeResp(resp);
         	 //commonService.createSmsOperLog("6", "气象局圈划范围同步接口", "0", "气象局圈划范围");
		} catch (Exception e){
			retMsg="项目发送范围同步接口异常,error:"+e.getMessage();
			map.put("retCode", retCode);
		  	map.put("retMsg", retMsg);
			e.printStackTrace();
			//commonService.createSmsOperLog("6", "气象局圈划范围同步接口", "1", "气象局圈划范围");
		}
 	  	return map;
	}
	private JSONObject initSynScopeReq(JSONObject parm){
		  String longAndLats = parm.getString("longAndLats");
		  if(longAndLats!=null&&!"".equals(longAndLats)){
			  longAndLats = longAndLats.replace('+', '|');
			  parm.put("longAndLats", longAndLats);
		  }
	  	  return parm;
	}
	//报文解析
	private Map<String, Object> readSynScopeResp(String resp){
        String retCode="-1";
        String resultDesc = "";
        Map<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);
        	retCode = jsonObject.getString("resultCode");
            resultDesc = jsonObject.getString("resultDesc");
        }
        retMap.put("retCode", retCode);
        retMap.put("retMsg", resultDesc);
        return retMap;
    }
	/**
	 * desc:根据气象局地市编码查询地市名称
	 * @author zhangh
	 * @param cityId
	 * @return 地市名称
	 */
	public String findQXJCityName(String cityId){
		String QXJCityName = smsInterfacesMapper.findQXJCityName(cityId);
		return QXJCityName;
	}

	private String getStreamSeq() {
        String streamSeq = changeSynchronizationInterfaceService.getStreamSeq();
        log.debug("获取流水序列号：{}", streamSeq);
        return streamSeq;
    }

	public static String  toGPS(String longAndLats) throws UnsupportedEncodingException {
		   String[] longAndLatsArray = longAndLats.split("\\|") ;
		   String longAndLatGPS = "";
		   for (int i = 0; i < longAndLatsArray.length; i++) {
		      String[] simpleLongAndLat = longAndLatsArray[i].split(",") ;
		      if (simpleLongAndLat.length==2) {
		         String gps = SmsInterfacesService.BdToGPS(simpleLongAndLat[0], simpleLongAndLat[1]);
		         if (i ==0 ) {
		            longAndLatGPS  = gps;
		         }else {
		            longAndLatGPS  = longAndLatGPS+"|"+gps;
		         }
		      }else{
					 longAndLatGPS=longAndLatGPS+"|"+longAndLatsArray[i];
		      }
		   }
		   return  longAndLatGPS;
		}

}
